package com.app.controller;

import cn.hutool.captcha.LineCaptcha;
import com.app.service.impl.CaptchaService;
import org.springframework.stereotype.Controller;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.OutputStream;

@Controller
@RequestMapping("captcha")
public class JcaptchaImageCreater {
    CaptchaService captchaService;

    public JcaptchaImageCreater(CaptchaService captchaService) {
        this.captchaService = captchaService;
    }

    @GetMapping
    void handleRequest(String captcha_id, HttpServletRequest request,HttpServletResponse response){
        System.out.println("captcha_id = " + captcha_id);
        if (ObjectUtils.isEmpty(captcha_id)){
            captcha_id=request.getHeader("captcha_id");
            if (ObjectUtils.isEmpty(captcha_id)) return;
        }
        response.setHeader("Cache-Control", "no-store");
        response.setHeader("Pragma", "no-cache");
        response.setDateHeader("Expires", 0L);
        response.setContentType("image/jpeg");
        LineCaptcha captcha = captchaService.getCaptchaById(captcha_id);
        try(OutputStream os=response.getOutputStream()) {
            captcha.write(os);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
